package cn.kennylee.codehub.mq.lip.integration;

import cn.kennylee.codehub.mq.lip.integration.base.IntegrationMqConsumerAnnoProcessor;
import cn.kennylee.codehub.mq.lip.integration.base.anno.MqListenerGenerator;
import cn.kennylee.codehub.mq.lip.integration.rocketmq.RocketMqConsumerGenerator;
import cn.kennylee.codehub.mq.lip.integration.rocketmq.listener.AbstractRocketMqListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

import java.util.List;

/**
 * <p> MQ集成，基础配置 </p>
 * <p>Created on 2025/4/18.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@AutoConfiguration
@Slf4j
@ConditionalOnClass({RocketMQAutoConfiguration.class})
@Import(RocketMQAutoConfiguration.class)
@ConditionalOnProperty(prefix = "app.mq.integration", name = "enable", havingValue = "true", matchIfMissing = true)
public class IntegrationMqConfig {

    /**
     * RocketMQ消费者生成器
     *
     * @return RocketMQ消费者生成器
     */
    @Bean
    @ConditionalOnClass({RocketMQTemplate.class, AbstractRocketMqListener.class})
    @ConditionalOnProperty(prefix = "app.mq.integration.consumer", name = "enable", havingValue = "true", matchIfMissing = true)
    RocketMqConsumerGenerator rocketMqConsumerGenerator() {
        return new RocketMqConsumerGenerator();
    }

    /**
     * 消费者注解处理器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "app.mq.integration.consumer", name = "enable", havingValue = "true", matchIfMissing = true)
    public IntegrationMqConsumerAnnoProcessor integrationMqConsumerAnnoProcessor(List<MqListenerGenerator> mqListenerGenerators) {

        IntegrationMqConsumerAnnoProcessor processor = new IntegrationMqConsumerAnnoProcessor();

        // 如果有RocketMQ消费者生成器，则添加到处理器中
        mqListenerGenerators.forEach(generator -> processor.addGenerator(generator.supportType(), generator));

        if (mqListenerGenerators.isEmpty()) {
            log.warn("未发现任何 MqListenerGenerator 实现，注解处理器将无法工作");
        }

        return processor;
    }
}
